package main

import (
	"log"
	"net/http"
	"runtime"
	"time"

	"./router"
	_ "github.com/go-sql-driver/mysql"
	"github.com/streadway/amqp"
	"github.com/tungyao/cedar"
	cedar_session "github.com/tungyao/cedar-session"
)

func main() {
	x := cedar.NewRouter()
	r := cedar_session.NewSession(x, cedar_session.LOCAL, "localhost")
	r.Get("/", router.Wss, nil)
	r.Group("/api", func(groups *cedar_session.Group) {
		groups.Group("/uuid", func(groups *cedar_session.Group) {
			groups.Get("/create", router.CreateUUID, nil)
		})
	})
	r.Get("/get/all", router.GetAllClient, nil)

	// 用来建立为每一个app 注册用户
	// 需要提交appid和secret
	// 返回 {"name":"xxx","uuid":"xxxx-xxxx-xxxx",time:1231231}
	// uuid 是唯一的 请注意保管
	r.Post("/create/user", router.CreateUser, nil)

	// 用来创建app
	// 需要先注册账号
	// 然后去申请app
	// 会返回 {appid:"xxx",secret:"xxxx"}
	// 请注意保存
	// 以后的所用步骤都会用上
	r.Get("/create/app", router.CreateApp, nil)
	r.Post("/create/group", router.CreateGroup, nil)
	r.Post("/join/group", router.JoinGroup, nil)
	// 还得有个来判断用户是否在线
	r.Get("/get/user/online", router.GetUserOnline, nil)
	if err := http.ListenAndServe(":8000", r.Handler); err != nil {
		panic(err)
	}
}

// 接受队列请求
// 这是一个完整的应用 写在这里只是因为 方便测试
func init() {
	runtime.GOMAXPROCS(4)
	// 连接mysql
	DB := router.DB
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	if err != nil {
		conn.Close()
		log.Fatalln(err)
	}
	ch, err := conn.Channel()
	if err != nil {
		ch.Close()
		log.Fatalln(err)
	}

	// TODO 监听创建用户
	imCreateUser, err := ch.QueueDeclare(
		"im_create_user", // name
		true,             // durable
		false,            // delete when unused
		false,            // exclusive
		false,            // no-wait
		nil,              // arguments
	)
	// 设置Qos
	err = ch.Qos(
		1,     // prefetch count
		0,     // prefetch size
		false, // global
	)
	imCreateUserMsgs, err := ch.Consume(imCreateUser.Name, "", false, false, false, false, nil)
	if err != nil {
		log.Panicln(err)
	}
	go func() {
		log.Println("listen rabbitMQ")
		for d := range imCreateUserMsgs {
			// 接受到消息
			d.Ack(false)
			log.Println("Received a message ", string(d.Body))
			// 写入sql 只是为了一个统计多少个用户
			// 临时用户不需要注册
			user := &router.ImCreateUser{}
			user.UnmarshalJSON(d.Body)
			stmt, _ := DB.Prepare("insert into user set uuid=?,name=?,create_time=?,multi_name=?,appid=?")
			//  写入注册表
			stmt.Exec(user.UUID, user.Name, user.Time, user.UUID+"|"+user.Name, user.Appid)
		}
	}()
	// !------------

	// TODO 监听加入群组
	imCreateGroups, err := ch.QueueDeclare("im_join_group", true, false, false, false, nil)
	err = ch.Qos(1, 0, false)
	if err != nil {
		log.Panicln(err)
	}
	imCreateGroupMsgs, err := ch.Consume(imCreateGroups.Name, "", false, false, false, false, nil)
	go func() {
		for v := range imCreateGroupMsgs {
			v.Ack(false)
			group := router.ImCreateGroup{}
			group.UnmarshalJSON(v.Body)
			row := DB.QueryRow("select name from `group` where gid=?", group.Gid)
			row.Scan(&group.Name)
			stmt, err := DB.Prepare("insert into `group` set gid=?,name=?,create_user=?,create_user_id=?,status=1,create_time=?")
			if err != nil {
				log.Panicln(err)
			}
			_, err = stmt.Exec(group.Gid, group.Name, group.CreateUser, group.CreateUserId, time.Now().Unix())
			if err != nil {
				log.Panicln(err)
			}
		}
	}()
	// !------------
}
